package com.ukao.pad.ui.clothingQuery;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.percent.PercentRelativeLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gprinterio.GpDevice;
import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.pad.R;
import com.ukao.pad.adapter.ClothingAnnexListAdapter;
import com.ukao.pad.base.MvpFragment;
import com.ukao.pad.bean.ClothesOperateStatusBean;
import com.ukao.pad.bean.ClothingInformationBean;
import com.ukao.pad.bean.ProductRelImgBean;
import com.ukao.pad.bean.ReceiptBean;
import com.ukao.pad.bean.StringBean;
import com.ukao.pad.dialog.ClothesOperateStatusDialogFragment;
import com.ukao.pad.eventbus.MembershipCardEvent;
import com.ukao.pad.listener.MyOnItemClickListener;
import com.ukao.pad.presenter.ClothingInformationPresenter;
import com.ukao.pad.printer.CheckPrinterHelper;
import com.ukao.pad.printer.PrinterHelper;
import com.ukao.pad.printer.PrinterReceipt;
import com.ukao.pad.ui.packPackag.PhotoActivity;
import com.ukao.pad.usbrfidreader.UsbrfidReaderHelper;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.GsonUtil;
import com.ukao.pad.utils.KeyBoardUtil;
import com.ukao.pad.utils.T;
import com.ukao.pad.view.ClothingInformationView;
import com.ukao.pad.widget.ClearEditText;
import com.ukao.pad.widget.RecycleViewDivider;
import com.ukao.pad.widget.StateButton;
import com.ukao.pad.widget.StateImageView;

import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 查询衣服信息
 */
public class ClothingInformationFragment extends MvpFragment<ClothingInformationPresenter> implements ClothingInformationView{
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;
    private Unbinder unbinder;
    @BindView(R.id.search_input_text)
    ClearEditText  mSearchInputText;
    @BindView(R.id.search_btn)
    StateImageView searchBtn;
    @BindView(R.id.rifd_btn)
    StateImageView rifdBtn;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.my_recycler_view)
    RecyclerView MyRecyclerView;
    @BindView(R.id.product_name)
    TextView  tvProductName;
    @BindView(R.id.tv_clothing_code)
    TextView tvClothingCode;
    @BindView(R.id.tv_service_name)
    TextView tvServiceName;
    @BindView(R.id.tv_photo_amount)
    TextView  tvPhotoCount;
    @BindView(R.id.tv_query_picture)
    TextView  tvQueryPicture;    //查看按钮
    @BindView(R.id.tv_color_name)
    TextView tvColorName;
    @BindView(R.id.print_receipt_btn)
    StateButton printBtn;
    @BindView(R.id.tv_brand_name)
    TextView tvBrandName;
    @BindView(R.id.tv_attach_content)
    TextView tvAttachContent;
    @BindView(R.id.tv_flaw_content)
    TextView tvFlawContent;
    @BindView(R.id.tv_laundry_result)
    TextView tvLaundryResult;
    @BindView(R.id.tv_order_no)
    TextView  tvOrder;
    @BindView(R.id.tv_operator_name)
    TextView tvOperatorName;
    @BindView(R.id.tv_convey_type)
    TextView tvConveyType;
    @BindView(R.id.tv_pass_process)
    TextView tvPassProcess;
    //衣服百分比相对布局
    @BindView(R.id.clothing_percent_layout)
    PercentRelativeLayout  mPercentRelativeLayout;
    private ArrayList<StringBean> mFlawDescList;
    private ArrayList<StringBean> mEffectDescList;
    private ArrayList<String> mPhotoData = new ArrayList<>();
    private ClothingInformationBean clothingInformation;
    private ClothingAnnexListAdapter clothingAttachmentListAdapter;  //衣物附件的Adapter
    private String  clothesId;  //衣物id



    public ClothingInformationFragment() {

    }


    // TODO: Rename and change types and number of parameters
    public static ClothingInformationFragment newInstance(String param1, String param2) {
        ClothingInformationFragment fragment = new ClothingInformationFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected ClothingInformationPresenter createPresenter() {
        return new ClothingInformationPresenter(this);
    }

    @Override
    protected void initView() {
        mSearchInputText.requestFocus();
        UsbrfidReaderHelper.getInstance().readCardNum();
        //测试用的衣物条码1194137306563，1194787480290, 没有附件的1191193516759
//     mSearchInputText.setText("1194787480290");
//            super.mvpPresenter.requestClothingInformation("1194787480290");
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       View view =inflater.inflate(R.layout.fragment_query_commodity_info, container, false);
        unbinder = ButterKnife.bind(this,view);
        return view;
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
        initAdapter();
    }
    protected void initListener() {
        //输入框 监听回车键
        mSearchInputText.setOnEditorActionListener(mOnEditorAction);
    }
    @Override
    protected void initAdapter() {
        initLinearRecyclerView(MyRecyclerView);
        //添加分割线
      MyRecyclerView.addItemDecoration(new RecycleViewDivider(getActivity(),
              LinearLayoutManager.HORIZONTAL));
        List<ClothingInformationBean.AnnexListBean> list=new ArrayList<>();
        clothingAttachmentListAdapter=new ClothingAnnexListAdapter(getActivity(),list);
        MyRecyclerView.setAdapter(clothingAttachmentListAdapter);
        clothingAttachmentListAdapter.setOnItemClickListener(mOnItemClick);
    }
    /**
     * 右边附件列表item 点击事件
     */
    private OnItemClickListener mOnItemClick=new MyOnItemClickListener(){
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            TextView textView =(TextView)view.findViewById(R.id.tv_clothing_code);
            ClothingInformationBean.AnnexListBean bean=clothingAttachmentListAdapter.getDatas().get(i);
            mvpPresenter.requestSingleClothingOperateRecord(_mActivity,String.valueOf(bean.getId()),
                    bean.getProductName(),textView.getText().toString());
        }
    };

    // 用户看见的时候
    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
    }

    @Override
    public boolean onBackPressedSupport() {
        return super.onBackPressedSupport();
    }


    public void onButtonPressed(Uri uri) {
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        UsbrfidReaderHelper.getInstance().cancelReadCardNum();  //取消读芯片
    }

    @Override
    public void loadFinishSuccess() {

    }

    /**
     * 监听回车键
     */
    TextView.OnEditorActionListener mOnEditorAction = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) {
                searchScanCode();
            }
            return false;
        }
    };

    /**
     * 搜索扫码的条码
     */
    private void searchScanCode(){
        String strScanCode = getText(mSearchInputText);
        if (strScanCode.isEmpty()) return;
        mvpPresenter.requestClothingInformation(strScanCode);
    }
    /**
     * 点击事件
     * @param view
     */
    @OnClick({R.id.print_receipt_btn,R.id.tv_query_picture,R.id.search_btn,R.id.rifd_btn,R.id.tv_order_no,
            R.id.clothing_percent_layout})
    public void onViewClicked(View view) {
            switch (view.getId()){
                case R.id.print_receipt_btn:   //打印小票
                    if(clothingInformation!=null)
                        mvpPresenter.printReceipt(getActivity(),clothingInformation.getOrderId()+"");
                    break;
                case R.id.tv_query_picture:  //查看相片
                    if (CheckUtils.isEmpty(mPhotoData)) return;
                    Intent mIntent = new Intent(getActivity(), PhotoActivity.class);
                    mIntent.putStringArrayListExtra(ARG_PARAM1, mPhotoData);
                    mIntent.putExtra(ARG_PARAM2, 0);
                    startActivity(mIntent);
                    break;
                case R.id.search_btn:   //搜索按钮
                    String  string =getText(mSearchInputText);
                    if(!TextUtils.isEmpty(string)){
                        super.mvpPresenter.requestClothingInformation(string);
                    }
                    break;
                case R.id.rifd_btn:   //射频识别
                    UsbrfidReaderHelper.getInstance().readCardNum();
                    break;
                case R.id.tv_order_no:
                    //启动订单的
                    if(!TextUtils.isEmpty(tvOrder.getText().toString())){
                        finish();
                        start(OrderInformationFragment.newInstance(clothingInformation.getOrderNo(),""));
                    }
                    break;
                case R.id.clothing_percent_layout:  //衣物名称的布局
                    if(!TextUtils.isEmpty(clothesId)){
                        mvpPresenter.requestSingleClothingOperateRecord(_mActivity,clothesId,
                                tvProductName.getText().toString(),tvClothingCode.getText().toString());
                    }
                    break;
            }
    }
    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe()
    public void  onMessageEvent(MembershipCardEvent event){
        switch (event.getMessage()) {
            case cardNum:/*成功*/
                String rfidSecretCard = (String) event.getData();
                mSearchInputText.setText(rfidSecretCard);
                searchScanCode();
                break;
        }

    }
    /**
     * 请求焦点，清空数据
     * 隐藏软件盘
     */
    private void cleanCode() {
        mSearchInputText.setText("");
        mSearchInputText.requestFocus();
        KeyBoardUtil.hideInputmethod(mSearchInputText);
    }
    /**
     * 请求成功
     */
    @Override
    public void requestSuccess(ClothingInformationBean ci) {
        clothingInformation=ci;
        clothesId= String.valueOf(ci.getId());
         if(!TextUtils.isEmpty(clothingInformation.getStoreName())||!TextUtils.isEmpty(clothingInformation.getStoreMark())){
             tvShopName.setText(clothingInformation.getStoreMark()+" "+clothingInformation.getStoreName());
         }else {
             tvShopName.setText("");
         }
         String inputCode=getText(mSearchInputText);
         if(!TextUtils.isEmpty(clothingInformation.getProductName())){
             tvProductName.setText(clothingInformation.getProductName()); //设置产品名
         }else {
             tvProductName.setText("");

         }
         if(!TextUtils.isEmpty(clothingInformation.getBindAliasCode())){
             tvClothingCode.setText(clothingInformation.getBindAliasCode());
         }else if(!TextUtils.isEmpty(clothingInformation.getBindCode())){
             tvClothingCode.setText(clothingInformation.getBindCode());
         }else if(!TextUtils.isEmpty(clothingInformation.getScanCode())){
             tvClothingCode.setText(clothingInformation.getScanCode());
         }else {
             tvClothingCode.setText("");
         }
         if(inputCode.equals(clothingInformation.getScanCode())||inputCode.equals(clothingInformation.getBindCode())
                 ||inputCode.equals(clothingInformation.getBindAliasCode())){
             mPercentRelativeLayout.setBackgroundResource(R.drawable.shape_clothin_selected_bg);
         }else {
             mPercentRelativeLayout.setBackgroundResource(R.drawable.shape_edit_text_black);
         }

        tvConveyType.setText("输"+clothingInformation.getTranNum()+"");  //输出线
        //设置衣物状态
        if(!TextUtils.isEmpty(clothingInformation.getStatusText())){
            if(clothingInformation.getStatusText().trim().equals("已洗完")){
                tvPassProcess.setTextColor(getResources().getColor(R.color.green));
            }else if(clothingInformation.getStatusText().trim().equals("洗涤中")){
                tvPassProcess.setTextColor(getResources().getColor(R.color.warm_red));
            }else {
                tvPassProcess.setTextColor(getResources().getColor(R.color.white));
            }
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d1=new Date(clothingInformation.getStatusTime());
            String strTime=format.format(d1);
            tvPassProcess.setText(clothingInformation.getStatusText()+"\n"+strTime);  //经过流程和时间
        }else {
            tvPassProcess.setText("");
            tvPassProcess.setTextColor(getResources().getColor(R.color.white));
        }
        tvOperatorName.setText(clothingInformation.getStatusWorkName());  //操作人员
        String serviceName;
        if(clothingInformation.getServiceName()==null){
            serviceName="";
        }else {
            serviceName=clothingInformation.getServiceName();
        }
        tvServiceName.setText(serviceName);
         //照片数量
        if(!TextUtils.isEmpty(clothingInformation.getPicCnt())){
            tvPhotoCount.setText(clothingInformation.getPicCnt());
        }else {
            tvPhotoCount.setText("");
        }
        if(clothingInformation.getProductImgList()!=null){
            for (ProductRelImgBean productRelImgBean : clothingInformation.getProductImgList()) {
                mPhotoData.add(productRelImgBean.getCameraImg());
            }
        }
        //
        String  color="";
        Gson  gson=  GsonUtil.getInstance();
        if(!TextUtils.isEmpty(clothingInformation.getColorDesc())){
            List<StringBean> mColorDescList = gson.fromJson(clothingInformation.getColorDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            StringBuffer mColorBuffer1 = new StringBuffer();
            for (int i = 0; i < mColorDescList.size(); i++) {
                if (i != mColorDescList.size() - 1) {
                    mColorBuffer1.append(mColorDescList.get(i).getName() + "/");
                } else {
                    mColorBuffer1.append(mColorDescList.get(i).getName());
                }
            }
            color= mColorBuffer1.toString();
        }
        tvColorName.setText(color);
        tvBrandName.setText(clothingInformation.getBrandName());  //品牌的名字
        //附加服务
        if (!CheckUtils.isEmpty(clothingInformation.getAddServiceDesc())) {
            List<StringBean> mServiceDescList = gson.fromJson(clothingInformation.getAddServiceDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            String service = "";
            for (StringBean item : mServiceDescList) {
                service = service + item.getName() + CheckUtils.isEmptyNumber(item.getAmt()) + "元" + ",";
            }
            if (service.endsWith(","))
                service = service.substring(0, service.length() - 1);
            tvAttachContent.setText(service); /* 附加f服务  */
        } else {
            tvAttachContent.setText("");
        }
        //瑕疵
        if (!CheckUtils.isEmpty(clothingInformation.getFlawDesc())) {
            mFlawDescList = gson.fromJson(clothingInformation.getFlawDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            String strFlawDesc = "";
            for (StringBean item : mFlawDescList) {
                strFlawDesc = strFlawDesc + item.getName() + "/";
            }
            if (strFlawDesc.endsWith("/"))
                strFlawDesc = strFlawDesc.substring(0, strFlawDesc.length() - 1);
            tvFlawContent.setText(strFlawDesc); /*瑕疵*/
        } else {
            tvFlawContent.setText("");
        }
        //洗后效果
        if (!CheckUtils.isEmpty(clothingInformation.getEffectDesc())) {
            mEffectDescList = gson.fromJson(clothingInformation.getEffectDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            String strEffectDesc = "";
            for (StringBean item : mEffectDescList) {
                strEffectDesc = strEffectDesc + item.getName() + "/";
            }
            if (strEffectDesc.endsWith("/"))
                strEffectDesc = strEffectDesc.substring(0,strEffectDesc.length() - 1);
            tvLaundryResult.setText(strEffectDesc); /*洗后效果*/
        } else {
            tvLaundryResult.setText("");
        }
        this.cleanCode();
            if(!TextUtils.isEmpty(clothingInformation.getOrderNo())){
                //订单号
                tvOrder.setText("订单:"+clothingInformation.getOrderNo());
            }
        //判断衣物附件被选中
        if(clothingInformation.getAnnexList()!=null){
            for (ClothingInformationBean.AnnexListBean bean : clothingInformation.getAnnexList()) {
                if (inputCode.equals(bean.getBindCode()) || inputCode.equals(bean.getScanCode()) ||
                        inputCode.equals(bean.getBindAliasCode())) {
                    bean.setChecked(true);
                }
            }
        }
        clothingAttachmentListAdapter.setSelectedItem(inputCode);//设置衣物附件选中的条码
        clothingAttachmentListAdapter.setDatas(clothingInformation.getAnnexList());
    }

    /**
     * 请求失败！
     * @param error
     */
    @Override
    public void requestFailure(String error) {
        T.show(error); //显示错误信息
        cleanCode();
    }

    /**
     * 打印小票
     * @param receiptBean
     */
    @Override
    public void loadReceiptData(ReceiptBean receiptBean) {
        if (receiptBean.getOutPrintType() && CheckPrinterHelper.isReceipt()) { /*是否用热敏小票打印机*/
            PrinterReceipt mPrinterReceipt = PrinterReceipt.getInstance();
            GpDevice mDevice = new GpDevice();
            mPrinterReceipt.printGp80(receiptBean, mDevice);
        } else if (CheckPrinterHelper.isWashprinter()) {  /*打标小票*/
            PrinterHelper.getInstance().printTsc247Receipt(receiptBean);
        }
    }

    /**
     * 接收衣物操作详情
     * @param List
     * @param clothesName
     * @param clothesCode
     */
    @Override
    public void receiveClothesOperateData(List<ClothesOperateStatusBean> List, String clothesName, String clothesCode) {
        ArrayList<ClothesOperateStatusBean> arrayList= (ArrayList<ClothesOperateStatusBean>) List;
        if(arrayList.size()>=1){
            ClothesOperateStatusDialogFragment cos=  ClothesOperateStatusDialogFragment.newInstance(arrayList,clothesName,clothesCode);
            cos.show(getChildFragmentManager(),cos.getClass().getName());
        }else {
            T.show("数据是null");
        }
    }


    public void loadReceiptData() {

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
